const { app, BrowserWindow, ipcMain, Menu, Tray, screen } = require('electron')
const path = require('path')

let mainWindow
let tray

// 桌宠配置
const PET_CONFIG = {
  width: 400,
  height: 600,
  alwaysOnTop: true,
  frame: false,
  transparent: true,
  resizable: false,
  skipTaskbar: false
}

function createWindow() {
  // 获取屏幕尺寸
  const { width: screenWidth, height: screenHeight } = screen.getPrimaryDisplay().workAreaSize
  
  // 窗口默认位置：右下角
  const x = screenWidth - PET_CONFIG.width - 50
  const y = screenHeight - PET_CONFIG.height - 50

  mainWindow = new BrowserWindow({
    width: PET_CONFIG.width,
    height: PET_CONFIG.height,
    x: x,
    y: y,
    frame: PET_CONFIG.frame,
    transparent: PET_CONFIG.transparent,
    resizable: PET_CONFIG.resizable,
    alwaysOnTop: PET_CONFIG.alwaysOnTop,
    skipTaskbar: PET_CONFIG.skipTaskbar,
    backgroundColor: '#00000000',
    hasShadow: true,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
      webSecurity: false, // 允许跨域请求后端
    },
    icon: path.join(__dirname, '../src/assets/touxiang.png')
  })

  // 开发环境加载 Vite 开发服务器，生产环境加载打包后的文件
  const isDev = process.env.NODE_ENV !== 'production'
  
  if (isDev) {
    mainWindow.loadURL('http://localhost:3001')
    // 开发模式下打开开发者工具
    // mainWindow.webContents.openDevTools({ mode: 'detach' })
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  // 窗口关闭时的处理
  mainWindow.on('closed', () => {
    mainWindow = null
  })

  // 创建系统托盘
  createTray()

  // 监听来自渲染进程的消息
  setupIPC()
}

function createTray() {
  // 托盘图标路径（你可以换成自己的图标）
  const trayIconPath = path.join(__dirname, '../src/assets/touxiang.png')
  
  tray = new Tray(trayIconPath)
  
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示/隐藏',
      click: () => {
        if (mainWindow.isVisible()) {
          mainWindow.hide()
        } else {
          mainWindow.show()
        }
      }
    },
    {
      label: '置顶',
      type: 'checkbox',
      checked: PET_CONFIG.alwaysOnTop,
      click: (menuItem) => {
        const shouldOnTop = menuItem.checked
        mainWindow.setAlwaysOnTop(shouldOnTop)
        PET_CONFIG.alwaysOnTop = shouldOnTop
      }
    },
    {
      type: 'separator'
    },
    {
      label: '重新加载',
      click: () => {
        mainWindow.reload()
      }
    },
    {
      label: '开发者工具',
      click: () => {
        mainWindow.webContents.openDevTools({ mode: 'detach' })
      }
    },
    {
      type: 'separator'
    },
    {
      label: '退出',
      click: () => {
        app.quit()
      }
    }
  ])
  
  tray.setToolTip('小七桌面助手')
  tray.setContextMenu(contextMenu)
  
  // 双击托盘图标显示窗口
  tray.on('double-click', () => {
    mainWindow.show()
  })
}

function setupIPC() {
  // 窗口拖动
  ipcMain.on('window-move-start', () => {
    const { x, y } = screen.getCursorScreenPoint()
    const [winX, winY] = mainWindow.getPosition()
    mainWindow.offsetX = x - winX
    mainWindow.offsetY = y - winY
  })

  ipcMain.on('window-moving', () => {
    const { x, y } = screen.getCursorScreenPoint()
    mainWindow.setPosition(
      x - (mainWindow.offsetX || 0), 
      y - (mainWindow.offsetY || 0)
    )
  })

  // 最小化到托盘
  ipcMain.on('minimize-to-tray', () => {
    mainWindow.hide()
  })

  // 关闭窗口
  ipcMain.on('close-window', () => {
    app.quit()
  })

  // 切换置顶
  ipcMain.on('toggle-always-on-top', () => {
    const shouldOnTop = !mainWindow.isAlwaysOnTop()
    mainWindow.setAlwaysOnTop(shouldOnTop)
    PET_CONFIG.alwaysOnTop = shouldOnTop
    mainWindow.webContents.send('always-on-top-changed', shouldOnTop)
  })

  // 调整窗口大小
  ipcMain.on('resize-window', (event, { width, height }) => {
    mainWindow.setSize(width, height)
  })
}

// 当 Electron 完成初始化时创建窗口
app.whenReady().then(createWindow)

// 所有窗口关闭时退出应用（macOS 除外）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// macOS 激活应用时重新创建窗口
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

